// @ts-nocheck
import React, { useRef, useState, useEffect } from 'react'
import { Image, StyleSheet, Switch, Text, TouchableOpacity, View, LayoutAnimation, Alert, SectionList } from 'react-native'
import icon_add from '../../assets/icon_add.png';
import icon_game from '../../assets/icon_game.png';
import icon_platform from '../../assets/icon_platform.png';
import icon_bank from '../../assets/icon_bank.png';
import icon_other from '../../assets/icon_other.png';
import icon_arrow from '../../assets/icon_arrow.png';
import AddModal from '../../components/AddModal'
import { load, remove, save } from '../../utils/Storage';

// 所有分类
const iconMap = {
  '游戏': icon_game,
  '平台': icon_platform,
  '银行卡': icon_bank,
  '其它': icon_other,
};

export default function Home() {

  // 获取ref
  const addAccountRef = useRef(null);

  // 控制显示密码开关
  const [passwordOpen, setPasswordOpen] = useState(false);

  // 每个分类的数据
  const [sectionData, setSectionData] = useState([]);

  // 分类的状态 （是否展开）
  const [sectionState, setSectionState] = useState({
    '游戏': true,
    '平台': true,
    '银行卡': true,
    '其它': true,
  })

  // 加载数据
  const loadData = () => {
    load('accountList').then((data: any) => {
      const accountList = JSON.parse(data)
      const gameList = accountList.filter((item:any) => item.type === '游戏') || [];
      const platformList = accountList.filter((item:any) => item.type === '平台') || [];
      const bankList = accountList.filter((item:any) => item.type === '银行卡') || [];
      const otherList = accountList.filter((item:any) => item.type === '其它') || [];

      // 分组列表
      const sectionData = [
        { type: '游戏', data: gameList },
        { type: '平台', data: platformList },
        { type: '银行卡', data: bankList },
        { type: '其它', data: otherList }
      ]

      LayoutAnimation.easeInEaseOut();
      setSectionData(sectionData as any);
    })
  }

  useEffect(() => {
    loadData();
  }, []);



  // 删除方法
  const deleteAccount = (account: any) => {
    load('accountList').then(data => {
      let accountList = JSON.parse(data as string);
      accountList = accountList.filter((item: { id: any; }) => item.id !== account.id);
      save('accountList', JSON.stringify(accountList)).then(() => {
        loadData();
      });
    })
  }




  const renderItem = ({ item, index, section }) => {
    if (!sectionState[section.type]) {
      return null;
    }
    return (
      <TouchableOpacity
        style={homeStyles.itemLayout}
        onPress={() => {
          addAccountRef.current.show(item);
        }}
        onLongPress={() => {
          const buttons = [
            { text: '取消', onPress: () => { } },
            { text: '确定', onPress: () => deleteAccount(item) }
          ];
          Alert.alert('提示', `确定删除「${item.name}」账号吗？`, buttons);
        }}
      >
        <Text style={homeStyles.nameTxt}>{item.name}</Text>
        <View style={homeStyles.accpwdLayout}>
          <Text style={homeStyles.accpwdTxt}>{`账号：${item.account}`}</Text>
          <Text style={homeStyles.accpwdTxt}>{`密码：${passwordOpen ? item.password : '********'}`}</Text>
        </View>
      </TouchableOpacity>
    )
  }

  const renderSectionHeader = ({ section }) => {
    return (
      <View style={[
        homeStyles.groupHeader,
      ]}>
        <Image style={homeStyles.typeImg} source={iconMap[section.type]} />
        <Text style={homeStyles.typeTxt}>{section.type}</Text>
        <TouchableOpacity
          style={homeStyles.arrowButton}
          onPress={() => {
            const copy = { ...sectionState }; // 回填之前的状态
            copy[section.type] = !copy[section.type];
            LayoutAnimation.easeInEaseOut();
            setSectionState(copy);
          }}
        >
          <Image
            style={[
              homeStyles.arrowImg,
              { transform: [{ rotate: sectionState[section.type] ? '0deg' : '-90deg' }] }
            ]}
            source={icon_arrow}
          />
        </TouchableOpacity>
      </View>
    )
  }

  const homeTitle = () => {
    return (
      <View style={homeStyles.titleLayout}>
        <Text style={homeStyles.titleTxt}>账号管理</Text>
        <Switch
          style={homeStyles.switch}
          value={passwordOpen}
          onValueChange={value => {
            setPasswordOpen(value);
          }}
        ></Switch>
      </View>
    )
  }

  return (
    <View style={homeStyles.root}>
      {homeTitle()}
      <SectionList
        sections={sectionData}
        keyExtractor={(item, index) => `${item}-${index}`}
        renderItem={renderItem}
        renderSectionHeader={renderSectionHeader} // 每个列表的头部
        contentContainerStyle={homeStyles.listContainer} // 内容容器样式
      ></SectionList>


      <TouchableOpacity
        style={homeStyles.addButton}
        activeOpacity={0.5}
        onPress={() => {
          // 触发ref的show方法
          addAccountRef.current.show();
        }}
      >
        <Image style={homeStyles.addImg} source={icon_add} />
      </TouchableOpacity>
      <View>
        <AddModal ref={addAccountRef} onLoad={loadData} />
      </View>


    </View>
  )
}

const homeStyles = StyleSheet.create({
  root: {
    width: '100%',
    height: '100%',
    backgroundColor: '#f0f0f0',
  },
  titleLayout: {
    width: '100%',
    height: 46,
    backgroundColor: 'white',
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  titleTxt: {
    fontSize: 18,
    color: '#333333',
    fontWeight: '500',
  },
  switch: {
    position: 'absolute',
    right: 20
  },
  addButton: {
    position: 'absolute',
    bottom: 64,
    right: 28,
  },
  addImg: {
    width: 56,
    height: 56,
    resizeMode: 'contain',
  },
  groupHeader: {
    width: '100%',
    height: 46,
    backgroundColor: 'white',
    borderTopLeftRadius: 12,
    borderTopRightRadius: 12,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 12,
    marginTop: 12,
  },
  typeImg: {
    width: 24,
    height: 24,
    resizeMode: 'contain',
  },
  listContainer: {
    paddingHorizontal: 12,
  },
  typeTxt: {
    fontSize: 16,
    color: '#333',
    fontWeight: '400',
    marginLeft: 16,
  },
  arrowButton: {
    position: 'absolute',
    right: 0,
    padding: 16,
  },
  arrowImg: {
    width: 20,
    height: 20,
  },
  itemLayout: {
    width: '100%',
    flexDirection: 'column',
    paddingHorizontal: 12,
    paddingVertical: 10,
    backgroundColor: 'white',
    borderTopWidth: 1,
    borderTopColor: '#E0E0E0',
  },
  nameTxt: {
    fontSize: 16,
    color: '#333',
    fontWeight: '400',
  },
  accpwdLayout: {
    width: '100%',
    flexDirection: 'row',
    alignItems: 'center',
  },
  accpwdTxt: {
    flex: 1,
    fontSize: 14,
    color: '#666666',
    marginTop: 12,
    marginBottom: 6,
  },
})